//
//  CQContactMainViewController.m
//  HiChat
//
//  Created by wqiong on 16/1/10.
//  Copyright © 2016年 wqiong. All rights reserved.
//

#import "CQContactMainViewController.h"
#import "CQRefreshTableViewController.h"
#import "CQAddViewController.h"
#import "CQContactModel.h"
#import "CQApplyViewController.h"

@interface CQContactMainViewController () <IChatManagerDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *listTableView;
@property (nonatomic, retain) NSMutableArray *listArr;
@property (nonatomic, retain) NSMutableDictionary *listDic;
@property (nonatomic, retain) NSMutableArray *keyArr;

@end

@implementation CQContactMainViewController

- (void)dealloc
{
    self.listTableView.delegate = nil;
    self.listTableView.dataSource = nil;
    [_listArr release];
    [_listDic release];
    [_keyArr release];
    [_listTableView release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    NSUserDefaults *useD = [NSUserDefaults standardUserDefaults];
    NSString *getName = [useD objectForKey:@"userName"];
    if (nil == getName) {
        
        self.listDic = nil;
        self.keyArr = nil;
        self.listArr = nil;
        
        [self.listTableView reloadData];
    } else {
        
        
        [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
        // 获取好友列表,在CQChatMainViewController中调用方法
        [[EaseMob sharedInstance].chatManager asyncFetchBuddyList];
    }

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"通讯录";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightAction)];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    // 获取好友列表,在CQChatMainViewController中调用方法
    [[EaseMob sharedInstance].chatManager asyncFetchBuddyList];
    
    
    self.listArr = [NSMutableArray array];
    self.listDic = [NSMutableDictionary dictionary];
    
    [self creatSubviews];
    
}

//跳转到添加好友界面
- (void)rightAction {
    CQAddViewController *addVC = [[CQAddViewController alloc] init];
    [self.navigationController pushViewController:addVC animated:YES];
    [addVC release];
}

/*!
 @method
 @brief 获取好友列表成功时的回调
 @discussion
 @param buddyList 好友列表
 @param error     错误信息
 */
- (void)didFetchedBuddyList:(NSArray *)buddyList
                      error:(EMError *)error
{
    
    self.listArr = [NSMutableArray arrayWithArray:buddyList];
    [self sortListArr];
    
    [self.listTableView reloadData];

    
}

//排序好友列表
- (void)sortListArr
{
    NSMutableArray *arrL = [NSMutableArray array];
    
    for (CQContactModel *model in self.listArr) {
//        NSString *key = [[ChineseToPinyin pinyinFromChiniseString:model.username] substringToIndex:1];
        NSString *key = [model.username substringToIndex:1];
        [arrL addObject:key];
    }
    
    [arrL sortUsingSelector:@selector(compare:)];
    
    for (NSString *key in arrL) {
        NSMutableArray *arr = [NSMutableArray array];
        for (CQContactModel *model in self.listArr) {
            if ([[model.username substringToIndex:1] isEqualToString:key]) {
                [arr addObject:model];
            }
        }
        [self.listDic setValue:arr forKey:key];
    }
    self.keyArr = [NSMutableArray arrayWithArray:self.listDic.allKeys];
    [self.listTableView reloadData];
}

- (void)creatSubviews
{
    self.listTableView = [[UITableView alloc] initWithFrame:self.view.frame];
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:self.listTableView.frame];
    imageV.image = [UIImage imageNamed:@"list"];
    self.listTableView.backgroundView = imageV;
    self.listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.listTableView.delegate = self;
    self.listTableView.dataSource = self;
    [self.view addSubview:self.listTableView];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.keyArr.count + 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return @"  ";
    }
    return [self.keyArr objectAtIndex:(section - 1)];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (0 == section) {
        return 1;
    }
    return [[self.listDic objectForKey:[self.keyArr objectAtIndex:(section - 1)]] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellList = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellList];
    
    if (nil == cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellList] autorelease];
        cell.backgroundColor = [UIColor clearColor];
    }
    
    if (0 == indexPath.section) {
        cell.textLabel.text = @"新的朋友";
        cell.imageView.image = [UIImage imageNamed:@"touxiang1"];
    } else {
    cell.textLabel.text = [[[self.listDic objectForKey:[self.keyArr objectAtIndex:(indexPath.section - 1)]] objectAtIndex:indexPath.row] username];
    cell.imageView.image = [UIImage imageNamed:@"touxiang1"];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (0 == indexPath.section && 0 == indexPath.section) {
        CQApplyViewController *applyVC = [[CQApplyViewController alloc] init];
        [self.navigationController pushViewController:applyVC animated:YES];
    } else {
    CQRefreshTableViewController *chatVC = [[CQRefreshTableViewController alloc]init];
    chatVC.navigationItem.title = [[self.listArr objectAtIndex:indexPath.row] username];
    chatVC.UserTo = [[[self.listDic objectForKey:[self.keyArr objectAtIndex:(indexPath.section - 1)]] objectAtIndex:indexPath.row] username];
    [self.navigationController  pushViewController:chatVC animated:YES];
    }
}

//索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.keyArr;
}

///处于编辑状态
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.listTableView setEditing:editing animated:animated];
}
///指定哪些可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
///指定编辑样式,添加或删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
///编辑完成
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    EMError *error = nil;
    // 删除好友
    //removeBuddy:要删除的用户
    //removeFromRemote:是否将自己从对方好友列表中移除
    //error:错误信息
    NSString *name = [[[self.listDic objectForKey:[self.keyArr objectAtIndex:(indexPath.section - 1)]] objectAtIndex:indexPath.row] username];
    
    BOOL isSuccess = [[EaseMob sharedInstance].chatManager removeBuddy:name removeFromRemote:YES error:&error];
    if (isSuccess && !error) {
        NSLog(@"删除成功");
    }
    
    NSString *key = [self.keyArr objectAtIndex:(indexPath.section - 1)];
    NSMutableArray *arr = [self.listDic objectForKey:key];
    if (UITableViewCellEditingStyleDelete == editingStyle) {
        [arr removeObjectAtIndex:indexPath.row];
        if (0 == arr.count) {
            [self.keyArr removeObjectAtIndex:(indexPath.section - 1)];
        }
        //        [self.listTableView reloadData];
    }
    
    
    [self.listTableView reloadData];
    
}



- (void)didReceiveMessage:(EMMessage *)message {
    //    NSLog(@"************%@",message);
    
//    EMChatText *txtChat = [[EMChatText alloc] initWithText:@"要发送的消息"];
//    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txtChat];
//    
//    // 生成message
//    EMMessage *qmessage = [[EMMessage alloc] initWithReceiver:@"test2" bodies:@[body]];
//    qmessage.messageType = eMessageTypeChat;
//    [[EaseMob sharedInstance].chatManager asyncSendMessage:qmessage progress:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
